package four;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : yang.xp
 * @date : 2021/12/14 14:58
 * @description : 对于condition的练习
 */
public class ConditionTest {
    private final int[] elements;
    private final Lock lock = new ReentrantLock();
    private final Condition notEmpty = lock.newCondition();
    private final Condition notFull = lock.newCondition();

    private int length = 0;

    public ConditionTest(int size) {
        elements = new int[size];
    }

    public static void main(String[] args) {
        ConditionTest conditionTest = new ConditionTest(2);
        Thread rs = new Thread(() -> {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            try {
                for (; ; ) {
                    String str = br.readLine();
                    int i = Integer.parseInt(str);
                    switch (i) {
                        case 1:
                            addThead(conditionTest);
                            continue;
                        case 2:
                            removeThead(conditionTest);
                            continue;
                        default:
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        rs.start();
    }

    public static void addThead(ConditionTest conditionTest) {
        Thread rs = new Thread(() -> conditionTest.add(1));
        rs.start();
    }

    public static void removeThead(ConditionTest conditionTest) {
        Thread rs = new Thread(() -> {
            try {
                conditionTest.remove();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        rs.start();
    }

    public void add(int value) {
        lock.lock();
        try {
            while (length == elements.length) {
                System.out.println("队列已满 请等待");
                notFull.await();
            }
            System.out.println("放入" + value);
            elements[length++] = value;
            notEmpty.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public int remove() throws InterruptedException {
        lock.lock();
        try {
            while (0 == length) {
                System.out.println("队列为空 请等待");
                notEmpty.await();
            }
            int element = elements[--length];
            System.out.println("取出" + element);
            notFull.signal();
            return element;
        } finally {
            lock.unlock();
        }
    }

}
